import router from "@/router/router";
import storage from 'store'
import store from '@/store'
import {RouteRecordRaw} from "vue-router";

const whiteList = ['/userLogin']

// 判断是否存在已添加的路由
const hasRoute = (to: any): boolean => {
    let flag = true;
    router.getRoutes().map((item: any) => {
        // 判断是否存在动态路由
        if (item.path.indexOf("/:") != -1) {
            if (to.path.indexOf(item.path.substr(0, item.path.indexOf("/:"))) != -1) {
                flag = false;
            }
        } else {
            if (item.path == to.path) {
                flag = false;
            }
        }
    });

    return flag;
};
router.beforeEach((to, from, next) => {
    if (storage.get('token')) {
        if (to.path === '/userLogin') {
            next({ path: '/' })
        } else {
            if (hasRoute(to)) {
                store.dispatch('setMenu').then(e => {
                    e.forEach((item: RouteRecordRaw) => {
                        router.addRoute(item)
                    })
                    router.addRoute({ path: '/:pathMatch(.*)*', redirect: '/404' })
                    const redirect = from.query.redirect as string | undefined
                    if (redirect && to.fullPath === redirect) {
                        next({ ...to, replace: true })
                    } else {
                        next({...to})
                    }
                }).catch((err) => {
                    next({ path: '/userLogin', query: { redirect: to.fullPath } })
                })
            }else {
                store.dispatch('setMenu').then(()=>{
                    next()
                })
            }
        }
    } else {
        if (whiteList.includes(to.path)) {
            next()
        } else {
            next({ path: '/userLogin', query: { redirect: to.fullPath } })
        }
    }
})

